<?php

namespace app\payment\admin;

use app\common\builder\ZBuilder;
use app\payment\model\PaymentGoodPaidCompany as PaymentGoodPaidCompanyModel;
use app\payment\model\PaymentPaidCompany as PaymentPaidCompanyModel;

/**
 * 优质代付通道控制器
 */
class GoodPaidCompany extends Index
{

    protected function initialize()
    {
        parent::initialize();
        if ($this->no_auth) {
            $this->error('权限不足！');
        }

        if (in_array(request()->action(), ['add'])) {
            if (!$this->add_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['edit'])) {
            if (!$this->edit_safe) {
                $this->error('NO');
            }
        }
        if (in_array(request()->action(), ['delete'])) {
            if (!$this->delete_safe) {
                $this->error('NO');
            }
        }
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        // 设置搜索参数
        $search = ['company_name' => '通道编号'];

        // 获取查询条件
        $map = $this->getMap();

        // 排序
        $order = $this->getOrder('sort asc,id asc');
        // 数据列表
        $data_list = PaymentGoodPaidCompanyModel::where($map)->order($order)->paginate();

        // 分页数据
        $page = $data_list->render();

        $items = [
            ['id', 'ID'],
            ['company_name', '通道编号', 'callback', function ($value) {
                $title = PaymentPaidCompanyModel::where(['name' => $value])->value('title');
                return $value . '<br/>' . $title;
            }, '', 'text-center'],
            ['create_time', '创建时间', 'datetime', '', 'Y-m-d H:i:s'],
            ['status', '状态', 'switch'],
            ['sort', '排序', 'text.edit'],
            ['right_button', '操作', 'btn']
        ];
        $hideCheckbox = false;
        if ($this->no_auth) {
            $hideCheckbox = true;
        }
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->hideCheckbox($hideCheckbox)
            ->setPageTitle('优质代付通道') // 设置页面标题
            ->setTableName('payment_good_paid_company') // 设置数据表名
            ->setPrimaryKey('id') // 设置主键名为id
            ->setSearch($search) // 设置搜索参数
            ->addColumns($items)
            ->addTopButtons('add,delete') // 批量添加顶部按钮
            ->addRightButton('see', ['title' => '查看', 'icon' => 'fa fa-fw fa-eye', 'href' => url('see', ['id' => '__id__'])], true)
            ->addRightButtons('edit,delete') // 批量添加右侧按钮
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch(); // 渲染页面
    }

    /**
     * 新增
     * @return mixed
     */
    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            // 验证
            $result = $this->validate($data, 'GoodPaidCompany');
            if (true !== $result) {
                $this->error($result);
            }

            $data['bind_merchant'] = str_replace('，', ',', str_replace(' ', '', $data['bind_merchant']));

            $info = PaymentGoodPaidCompanyModel::where(['company_name' => $data['company_name']])->find();
            if ($info) {
                $this->error("请刷新，数据已经存在！");
            }

            if ($temp = PaymentGoodPaidCompanyModel::create($data)) {
                // 记录行为
                action_log('payment_good_paid_company_add', 'payment_good_paid_company', $temp['id'], UID, json_encode($temp));
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }
        // 支付公司    
        $payment_company = PaymentPaidCompanyModel::where(['status' => 1])->order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc', 'name' => 'asc'])->column('title', 'name');

        $id = date('YmdHis');

        $items = [
            ['hidden', 'id', $id],
            ['select', 'company_name', '通道名称', '', $payment_company],
            ['textarea', 'tips', '通道说明', '该通道的具体说明'],
            ['text', 'sort', '排序', '', 100],
            ['radio', 'status', '状态', '', ['禁用', '启用'], 1],
            ['radio', 'paid_class', '代付分类', '', ['银行卡代付', '支付宝代付', '银行卡和支付宝'], 1],
            ['textarea', 'bind_merchant', '绑定商户号', '绑定中的商户号执行，多个商户号用逗号分隔（,）<code>空表示无限制</code>'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        $tips = "请勿填错！优质代付通道会优先执行！";
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增') // 设置页面标题
            ->setPageTips($tips)
            ->addFormItems($items)
            ->fetch();
    }

    /**
     * 查看
     * @param null $id 
     * @return mixed
     */
    public function see($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }
        // 获取数据
        $info = PaymentGoodPaidCompanyModel::where('id', $id)->field(true)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        // 支付公司    
        $payment_company = PaymentPaidCompanyModel::where([])->order('sort asc,name asc')->column('title', 'name');

        $items = [
            ['hidden', 'id', $id],
            ['static', 'company_name', '通道名称', '通道名称：' . $payment_company[$info['company_name']]],
            ['textarea', 'tips', '通道说明[:无]', '该通道的具体说明', '', 'disabled', ''],
            ['static', 'sort', '排序', '', 100],
            ['radio', 'status', '状态', '', ['禁用', '启用']],
            ['radio', 'paid_class', '代付分类', '', ['银行卡代付', '支付宝代付', '银行卡和支付宝']],
            ['textarea', 'bind_merchant', '绑定商户号[:无]', '绑定中的商户号执行，多个商户号用逗号分隔（,）<code>空表示无限制</code>', '', 'disabled', ''],
            ['datetime', 'create_time', '创建时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
            ['datetime', 'update_time', '更新时间', '', '', 'YYYY-MM-DD HH:mm:ss', 'disabled'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('查看') // 设置页面标题
            ->addFormItems($items)
            ->hideBtn('submit')
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 编辑
     * @param null $id 
     * @return mixed
     */
    public function edit($id = null)
    {
        if ($id === null) {
            $this->error('缺少参数！');
        }

        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();

            if ($this->merchant_info['trade_pwd'] != md5(md5(md5($data['trade_pwd'])))) {
                $this->error('交易密码不正确！');
            }

            unset($data['trade_pwd']);

            // 验证
            $result = $this->validate($data, 'GoodPaidCompany');
            if (true !== $result) {
                $this->error($result);
            }

            $data['bind_merchant'] = str_replace('，', ',', str_replace(' ', '', $data['bind_merchant']));

            if ($temp = PaymentGoodPaidCompanyModel::update($data)) {
                // 记录行为
                action_log('payment_good_paid_company_edit', 'payment_good_paid_company', $temp['id'], UID, json_encode($temp));
                $this->success('编辑成功', url('index'));
            } else {
                $this->error('编辑失败');
            }
        }

        // 获取数据
        $info = PaymentGoodPaidCompanyModel::where('id', $id)->find();
        if (!$info) {
            $this->error('不存在！');
        }

        // 支付公司    
        $payment_company = PaymentPaidCompanyModel::where(['status' => 1])->order(['group' => 'asc', 'sort' => 'asc', 'title' => 'asc', 'name' => 'asc'])->column('title', 'name');

        $items = [
            ['hidden', 'id', $id],
            ['select', 'company_name', '通道名称', '', $payment_company],
            ['textarea', 'tips', '通道说明', '该通道的具体说明'],
            ['text', 'sort', '排序', '', 100],
            ['radio', 'status', '状态', '', ['禁用', '启用'], 1],
            ['radio', 'paid_class', '代付分类', '', ['银行卡代付', '支付宝代付', '银行卡和支付宝'], 1],
            ['textarea', 'bind_merchant', '绑定商户号', '绑定中的商户号执行，多个商户号用逗号分隔（,）<code>空表示无限制</code>'],
            ['password', 'trade_pwd', '交易密码', '6-16位'],
        ];

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑') // 设置页面标题
            ->addFormItems($items)
            ->setFormData($info) // 设置表单数据
            ->fetch();
    }

    /**
     * 删除
     * @param array $record 
     * @return mixed
     */
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }

    /**
     * 启用
     * @param array $record 
     * @return mixed
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }

    /**
     * 禁用
     * @param array $record 
     * @return mixed
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }

    /**
     * 设置状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record 
     * @return mixed
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids_delete = is_array($ids) ? '' : $ids;
        $data = PaymentGoodPaidCompanyModel::where('id', 'in', $ids)->column('id');
        return parent::setStatus($type, ['payment_good_paid_company_' . $type, 'payment_good_paid_company', $ids_delete, UID, implode('、', $data)]);
    }

    /**
     * 快速编辑
     * @param array $record 行为日志
     * @return mixed
     */
    public function quickEdit($record = [])
    {
        $id = input('post.pk', '');
        $field = input('post.name', '');
        $value = input('post.value', '');
        $data = PaymentGoodPaidCompanyModel::where('id', $id)->value($field);
        $details = '字段(' . $field . ')，原值(' . $data . ')，新值：(' . $value . ')';
        return parent::quickEdit(['payment_good_paid_company_edit', 'payment_good_paid_company', $id, UID, $details]);
    }
}
